﻿using System.IO;
using System.Net;
using System.Text;
using System;

namespace YTPD.Lib
{
  public class WebClientImpl : WebClient
  {
    public const string CHROME_USER_AGENT =
       @"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.19 (KHTML, like Gecko) Chrome/0.4.154.18 Safari/525.19";

    public string DownloadString(string uri)
    {
      // used to build entire input
      var stringBuilder = new StringBuilder();

      // used on each read operation
      var buffer = new byte[8192];

      var request = WebRequest.Create(uri) as HttpWebRequest;
      request.UserAgent = CHROME_USER_AGENT;

      var response = request.GetResponse() as HttpWebResponse;
      var responseStream = response.GetResponseStream();

      int readBufferLength;

      do
      {
        readBufferLength = responseStream.Read(buffer, 0, buffer.Length);

        if (readBufferLength != 0)
        {
          var temporaryString = Encoding.ASCII.GetString(buffer, 0, readBufferLength);

          stringBuilder.Append(temporaryString);
        }
      }
      while (readBufferLength > 0);

      return stringBuilder.ToString();
    }

    public void DownloadFile(string uri, string fileName, UpdateProgress updateProgress)
    {
      // used to build entire input
      var fileStream = File.Create(fileName);

      // used on each read operation
      var buffer = new byte[8192];

      var request = WebRequest.Create(uri) as HttpWebRequest;
      request.UserAgent = CHROME_USER_AGENT;

      var response = request.GetResponse() as HttpWebResponse;
      var contentLength = response.ContentLength;
      var responseStream = response.GetResponseStream();

      int readBufferLength;
      do
      {
        readBufferLength = responseStream.Read(buffer, 0, buffer.Length);
        fileStream.Write(buffer, 0, readBufferLength);

        updateProgress(fileStream.Length, contentLength);
      }
      while (readBufferLength > 0);

      fileStream.Close();
    }
  }
}